<template>
    <el-card style="margin-top: 24px; border-radius: 16px;">
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <h3>历史运动记录</h3>
        <el-button type="primary" @click="showForm = true">添加运动</el-button>
      </div>
      <el-table :data="records" style="margin-top:20px;">
        <el-table-column prop="date" label="日期"/>
        <el-table-column prop="type" label="类型"/>
        <el-table-column prop="duration" label="时长(分钟)"/>
        <el-table-column prop="distance" label="距离(公里)"/>
        <el-table-column prop="calories" label="消耗(千卡)"/>
        <el-table-column prop="note" label="备注"/>
      </el-table>
      <el-dialog v-model="showForm" title="手动添加运动记录" width="400px">
        <el-form :model="form" @submit.prevent="submit">
          <el-form-item label="运动类型">
            <el-select v-model="form.type" placeholder="请选择">
              <el-option label="跑步" value="跑步"/>
              <el-option label="骑行" value="骑行"/>
              <el-option label="力量训练" value="力量"/>
            </el-select>
          </el-form-item>
          <el-form-item label="时长(分钟)">
            <el-input v-model.number="form.duration" type="number"/>
          </el-form-item>
          <el-form-item label="距离(公里)">
            <el-input v-model.number="form.distance" type="number"/>
          </el-form-item>
          <el-form-item label="消耗(千卡)">
            <el-input v-model.number="form.calories" type="number"/>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker v-model="form.date" type="date" placeholder="选择日期"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.note"/>
          </el-form-item>
          <el-button type="primary" native-type="submit">保存</el-button>
        </el-form>
      </el-dialog>
    </el-card>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import request from '@/utils/request'
  import dayjs from 'dayjs'
  
  const showForm = ref(false)
  const form = ref({
    type: '',
    duration: '',
    distance: '',
    calories: '',
    date: '',
    note: ''
  })
  const records = ref([])
  
  const submit = async () => {
    // 格式化日期为YYYY-MM-DD
    if (form.value.date) {
      form.value.date = dayjs(form.value.date).format('YYYY-MM-DD')
    }
    await request.post('/sport/record/', form.value)
    showForm.value = false
    await fetchRecords()
  }
  
  const fetchRecords = async () => {
    const res = await request.get('/sport/record/')
    records.value = res
  }
  
  onMounted(fetchRecords)
  </script> 